<?php

namespace App\Listeners;

use App\Events\teamActivityPaid;
use App\TeamFollow;
use App\TeamFound;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class HandleTeamActivityPaid
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  teamActivityPaid  $event
     * @return void
     */
    public function handle(teamActivityPaid $event)
    {
        $order = $event->order;
        if ($order->promotion_type == 'App\TeamActivity') {
            $follow = TeamFollow::where('order_id', $order->id)->first();
            $found = TeamFound::where('id', $follow->team_found_id)->first();
            // 开团者
            if ($follow->team_found_user_id == $follow->user_id) {
                $found->status = 'ACTIVE';
            }
            $found->join = $found->join + 1;
            // 开团成功
            if ($found->needer <= $found->join) {
                $found->status = 'SUCCESS';
                // 删除未支护订单
                $unpaidFollow = TeamFollow::where('team_found_id', $follow->team_found_id)
                    ->whereHas('order', function($query) {
                        return $query->where('pay_status', 0);
                    })->get();
                foreach ($unpaidFollow as $unpaid) {
                    $unpaid->order->delete();
                }
            }
            $found->save();
        }
    }
}
